<?php
/**
 * TinyCatPHP 极简、快速、创新、易用、高性能的PHP应用开发框架
 * User: CnTaiGe <hst042@163.com>
 * Date: 2017/11/19
 */

namespace TinyCatPHP\libs\utils;

use TinyCatPHP\libs\config\Config;

class Log
{
    protected static $logs = [];

    /**
     * 记录日志
     * @param $level string 日志级别
     * @param $msg
     */
    public static function record($level, $msg)
    {
        $levelArr = Config::get('log_level');
        if (in_array($level, $levelArr))
            self::$logs[] = date('Y-m-d H:i:s') . " [{$level}] " . '===> ' . $msg . PHP_EOL;
        if (PHP_SAPI === 'cli') {
            self::save();
            self::$logs = [];
        }
    }

    /**
     * 保存日志
     */
    public static function save()
    {
        if (count(self::$logs) !== 0) {
            $data = implode('', self::$logs);
            $file = Config::get('data_path') . '/logs/' . date('Y_m_d');
            if (file_exists($file . '.log') && filesize($file . '.log') > 3500000) {
                rename($file . '.log', $file . '_' . date('His') . '.log');
            }
            File::save($file . '.log', $data);
        }
    }
}